<?php

namespace App\Http\Controllers\Admin;

use App\Enums\GoodsClassStatusEnum;
use App\Models\Category;
use App\Models\GoodsClass;
use App\Requests\Admin\GoodsClass\GoodsClassIndexRequest;
use App\Requests\Admin\GoodsClass\GoodsClassSaveRequest;
use App\Requests\Admin\GoodsClass\GoodsClassSwitchStatusRequest;
use App\Requests\BaseRequest;
use App\Traits\CurdTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class GoodsClassController extends BaseController
{
    use CurdTrait;

    /**
     * @var GoodsClass
     */
    protected $curdModel;

    public function _init()
    {
        parent::_init();
        $this->setCurdModel(new GoodsClass());
    }

    /**
     * 列表
     *
     * @param BaseRequest $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/16
     */
    public function list(GoodsClassIndexRequest $request)
    {
        $paramId = $request->input('id');
        $paramName = $request->input('name');
        $paramBeginTime = $request->input('begin_time');
        $paramEndTime = $request->input('end_time');
        $paramStatus = $request->input('status');

        $where = function ($q) use ($paramId, $paramName, $paramBeginTime, $paramEndTime, $paramStatus) {
            if ($paramId) {
                $q->where('id', $paramId);
            }
            if ($paramName) {
                $q->where('name', 'like', '%' . $paramName . '%');
            }
            if ($paramBeginTime) {
                $q->where('create_time', '>=', $paramBeginTime);
            }
            if ($paramEndTime) {
                $q->where('create_time', '<=', $paramEndTime);
            }
            if ($paramStatus) {
                $q->where('status', $paramStatus);
            }
        };

        $paginate = $this->curdModel
            ->where($where)
            ->where('pid',0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->paginate($this->pageSize);

        // 查询各类状态的统计数据
        $statistics = [];
        $statusEnums = GoodsClassStatusEnum::values();
        $where = function ($q) use ($paramId, $paramName, $paramBeginTime, $paramEndTime, $paramStatus) {
            if ($paramId) {
                $q->where('id', $paramId);
            }
            if ($paramName) {
                $q->where('name', 'like', '%' . $paramName . '%');
            }
            if ($paramBeginTime) {
                $q->where('create_time', '>=', $paramBeginTime);
            }
            if ($paramEndTime) {
                $q->where('create_time', '<=', $paramEndTime);
            }
        };
        foreach ($statusEnums as $statusEnum) {
            $statistics[$statusEnum->getLowerName()] = $this->curdModel
                ->where($where)
                ->where('status', $statusEnum->getKey())
                ->count();
        }


        $data=$paginate->items();
        foreach ($data as &$item){
            $item['children']=$this->curdModel
                ->where('pid',$item['id'])
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'desc')
                ->get();
        }
        return $this->responseSuccess('', [
            'list' => $data,
            'total' => $paginate->total(),
            'statistics' => $statistics,
        ]);
    }

    /**
     * 所有品类
     */
    public function all()
    {
        $list = $this->curdModel->select('id', 'name', 'status')->get();
        return $this->responseSuccess('', $list);
    }

    /**
     * 详情
     *
     * @param \Illuminate\Http\Request $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function info(Request $request)
    {
        $id = $request->input('id');
        $model = $this->curdModel->find($id);
        if (empty($model)) {
            return $this->responseFail('数据不存在');
        }

        return $this->responseSuccess('', $model);
    }

    /**
     * 保存
     *
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function save(GoodsClassSaveRequest $request)
    {
        $id = $request->input('id');
        if ($id) {
            return $this->edit($request);
        }
        else {
            return $this->add($request);
        }
    }

    /**
     * 添加
     *
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2024/12/18
     */
    protected function add(GoodsClassSaveRequest $request)
    {
        $saveData = $request->validated();
        $name = $saveData['name'];

        if ($this->curdModel->where('name', $name)->exists()) {
            return $this->responseFail('名称已存在');
        }

        DB::beginTransaction();

        $row = $this->curdModel->create($saveData);
        if (!$row) {
            return $this->responseFail('添加失败');
        }

        DB::commit();

        $all_category = (new GoodsClass)->getApiAll();
        Redis::set(GoodsClass::goods_class_category, json_encode($all_category));


        return $this->responseSuccess('添加成功', ['id' => $row->getKey()]);
    }

    /**
     * 编辑
     *
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    protected function edit(GoodsClassSaveRequest $request)
    {
        $saveData = $request->validated();
        $id = $saveData['id'];

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        $name = $saveData['name'];
        if ($this->curdModel->where('name', $name)->where('id', '!=', $id)->exists()) {
            return $this->responseFail('名称已存在');
        }

        unset($saveData['id']);

        DB::beginTransaction();

        $res = $row->fill($saveData)->save();
        if (!$res) {
            return $this->responseFail('编辑失败');
        }

        DB::commit();

        $all_category = (new GoodsClass)->getApiAll();
        Redis::set(GoodsClass::goods_class_category, json_encode($all_category));


        return $this->responseSuccess('编辑成功', ['id' => $row->getKey()]);
    }

    /**
     * 删除
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        DB::beginTransaction();

        $res = $row->delete();
        if (!$res) {
            return $this->responseFail('删除失败');
        }

        DB::commit();

        $all_category = (new GoodsClass)->getApiAll();
        Redis::set(GoodsClass::goods_class_category, json_encode($all_category));


        return $this->responseSuccess('删除成功');
    }

    /**
     * 预览
     *
     * @param GoodsClassSwitchStatusRequest $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function switchStatus(GoodsClassSwitchStatusRequest $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');
        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        $row->update([
            'status' => $status,
        ]);

        $all_category = (new GoodsClass)->getApiAll();
        Redis::set(GoodsClass::goods_class_category, json_encode($all_category));


        return $this->responseSuccess();
    }

}
